package com.cch.android.activity.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsoluteLayout;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.cch.android.activity.ModelLandscapActivity;
import com.cch.android.activity.ModelLandscapActivity.SeekBarWordDialog;
import com.cch.android.activity.R;
import com.cch.android.imageutil.ColorPickerDialog;
import com.cch.android.util.Constant;
import com.cch.android.util.MyLog;

public class WordEditActivity extends Activity implements OnClickListener,OnTouchListener,OnSeekBarChangeListener{
	
	private FrameLayout view_lay;
	
	private AbsoluteLayout view_ab;
	  
    private ImageView mImageView;
    
    private Button effect_close,effect_save;
    
    private LinearLayout word_add_lay,word_bubble_lay,word_style_lay,word_view;
    
    private TextView wordText;
    
    private ColorPickerDialog dialog;
    /**
     * 编辑图片
     */
    private Bitmap mBitmap; 
    
	/**
	 * 变化后的图片
	 */
	private Bitmap bmpSet;
	
	/**
	 * 添加的文字内容
	 */
	private String wordStr;
	
	private Boolean flag = false;
	
	
	 private LinearLayout tone_view_lay;
	 
	 public static final int FLAG_SATURATION = 0x0;  
	/**
	 * 文字纵横坐标
	 */
	private int x = 0,y = 0,rawX=0,rawY=0;
	
	/**
	 * 文字颜色
	 */
	private int wordColor=Color.WHITE;
	/**
	 * 文字大小
	 */
	private int wordSize=30;
	
	private int m_screenWidth,m_screenHeight;
	
	private SeekBar mSeekBar;
	
	private Button mColorBtn;
	
	private Context context;
	
	  @Override
	   public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.model_setimage_wordedit);
		context = this;
		Intent intent = getIntent();
		
		
		mBitmap = intent.getParcelableExtra("imageBmp");
		wordStr = intent.getStringExtra("addWord");
		initView();
		
	}
	  /**
	   * 初始化数据
	   */
	  private void initView(){
		     m_screenWidth = Constant.m_screenWidth;
		     m_screenHeight = Constant.m_screenHeight;
		     word_view = (LinearLayout)findViewById(R.id.word_view);
		     tone_view_lay = (LinearLayout) findViewById(R.id.tone_view);
		     mSeekBar = (SeekBar)findViewById(R.id.word_size_seekbar);
		     mColorBtn = (Button)findViewById(R.id.word_color_btn);
		     effect_close = (Button) findViewById(R.id.setimage1_wordedit_colse);
		     effect_save= (Button) findViewById(R.id.setimage1_wordedit_save);
		     mImageView = (ImageView) findViewById(R.id.setimage1_wordedit_image);
		     view_ab= (AbsoluteLayout)findViewById(R.id.setimage1_wroidedit_lay);
//		     wordText = (TextView)findViewById(R.id.setimage1_wordedit_text);
		     
//		     view_lay = (FrameLayout) findViewById(R.id.setimage1_wroidedit_lay);
		     word_add_lay = (LinearLayout) findViewById(R.id.word_add);
		     word_bubble_lay = (LinearLayout) findViewById(R.id.word_bubble);
		     word_style_lay = (LinearLayout) findViewById(R.id.word_style);
		     
		     mSeekBar.setTag(0);
		     mSeekBar.setMax(60);
		     mSeekBar.setProgress(SeekBarWordDialog.FLAG_SIZE_PROGRESS);
		     mSeekBar.setOnSeekBarChangeListener(this);
		     mColorBtn.setOnClickListener(this);
		     effect_close.setOnClickListener(this);
		     effect_save.setOnClickListener(this);
		     word_add_lay.setOnClickListener(this);
		     word_bubble_lay.setOnClickListener(this);
		     word_style_lay.setOnClickListener(this);
	      
	        if(mBitmap!=null)
	           mImageView.setImageBitmap(mBitmap);
			if (wordStr != null) {
				wordText = new TextView(this);
				wordText.setTextColor(wordColor);
				wordText.setTextSize(wordSize);
				LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT, m_screenWidth / 2,
						m_screenHeight / 2);
				wordText.setLayoutParams(params);
				wordText.setText(wordStr);
				view_ab.addView(wordText);
				wordText.setOnTouchListener(this);
			}
	  }
	  @Override
	protected void onDestroy() {
		  if (mBitmap != null) {
				mBitmap.recycle();
				System.gc();
				mBitmap=null;
			}
			if (bmpSet != null) {
				bmpSet.recycle();
				System.gc();
				bmpSet=null;
			}
		super.onDestroy();
		
	}
	  @Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			// TODO Auto-generated method stub
			switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				backToMain();
				break;

			default:
				break;
			}
			return super.onKeyDown(keyCode, event);
		}
		@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.word_add://添加文字
			tone_view_lay.setVisibility(View.GONE);
			Intent intent = new Intent();
			intent.putExtra("imageBmp", mBitmap);
			intent.setClass(this, WordAddActivity.class);
			startActivity(intent);
			break;
		case R.id.word_bubble://添加泡泡
			break;
		case R.id.word_style://文字类型
			if (wordStr != null && wordText!=null) {
				tone_view_lay.setVisibility(View.VISIBLE);
				mColorBtn.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog = new ColorPickerDialog(context, wordText
								.getTextColors().getDefaultColor(), "",
								new ColorPickerDialog.OnColorChangedListener() {

									@Override
									public void colorChanged(int color) {
										wordText.setTextColor(color);
									}
								});
						dialog.show();
					}
				});
			}
			break;
		case R.id.setimage1_wordedit_colse:
				finish();
			break;
		case R.id.setimage1_wordedit_save:
			if(wordStr != null && wordText!=null )
			saveToMain();
			break;
		}
		}
		private void backToMain(){
			Intent intent = new Intent();
			intent.putExtra("imageBmp", mBitmap);
			intent.setClass(this, ModelLandscapActivity.class);
			startActivity(intent);
			finish();
		}
		/**
		 * 保存到sd卡 回到美化图片主界面
		 */
		private void saveToMain(){
			Intent intent = new Intent();
			int x,y;
			
			if(rawX==0)x=m_screenWidth/2;
			else x = rawX;
			if(rawY==0)y=m_screenHeight/2;
			else y = rawY;
			
			Bitmap bmp = getBmpAndWord(getSetBitmap(), wordText.getText().toString(),x,y);
			intent.putExtra("imageBmp", bmp);
			intent.setClass(this, ModelLandscapActivity.class);
			startActivity(intent);
			finish();
		}
		  /**
		   * 合成图片与文字
		   */
		private Bitmap getBmpAndWord(Bitmap bmp,String wordStr,int X ,int Y){
			if (bmp != null) {
				if (wordStr != null) {
					
					int w = bmp.getWidth();
					int h = bmp.getHeight();
					 Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888 ); 
					Canvas canvasTemp = new Canvas(newb);   
					int ww =canvasTemp.getWidth();
					int hh = canvasTemp.getHeight();
//	                canvasTemp.drawColor(wordColor);   
	                   
	                Paint p = new Paint(Paint.SUBPIXEL_TEXT_FLAG); 
	                String familyName ="宋体";   
	                Typeface font = Typeface.create(familyName,Typeface.NORMAL);  
	                p.setTypeface(font);  
	                p.setColor(wordText.getTextColors().getDefaultColor());  
	                p.setAntiAlias(true);
//	                p.setTextAlign(Paint.Align.CENTER);
	                p.setTextSize(wordText.getTextSize()*hh/m_screenHeight+12);   
	                canvasTemp.drawBitmap(bmp, 0,0,p);//画图   
	                
	                int x = X * ww/m_screenWidth;
					int y = Y *hh/m_screenHeight;
	                MyLog.log("画图x:"+x);
	                MyLog.log("画图y:"+y);
	                
	                canvasTemp.drawText(wordStr,x,y,p);   
	                canvasTemp.save(Canvas.ALL_SAVE_FLAG);  
	                canvasTemp.restore();  
					
	                MyLog.log("图片与文字叠加："+newb);
					return newb;
				} else {
					return bmp;
				}
			}
			return null;
		}  
		/**
		 * 得到处理的图片
		 * @return
		 */
		private Bitmap getSetBitmap(){
			if (mImageView != null) {
				if (bmpSet != null) {
					bmpSet.recycle();
					System.gc();
					bmpSet=null;
				}
				bmpSet = Constant.drawable2Bitmap(mImageView.getDrawable());
				return bmpSet;
			}
			return bmpSet;
		}
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			 MyLog.log("getAction："+event.getAction());
			  switch (event.getAction()) {
			 
			  case MotionEvent.ACTION_DOWN:
				  flag = true;
				  break;
			  case MotionEvent.ACTION_MOVE:
					// flag为true即控件被点到时，执行移动控件操作
				  if(flag){
					 x = (int) event.getX();
					 y = (int) event.getY();
					 rawX = (int) event.getRawX();
					 rawY = (int) event.getRawY();
					MyLog.log("移动x："+x);
					MyLog.log("移动y："+y);
					MyLog.log("移动xx："+rawX);
					MyLog.log("移动yy："+rawY);
					// 得到X，Y座标
					LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT, rawX, rawY);
					// 四参数分别为宽，高，X，Y座标，wrap_conent为根据内容自动调整
					// 后面-10,-40是我自己多次调试的结果，因为我发现如果不减，那个座标并不是在指头下，而是在指头的右下角
					// 暂时不知道什么原因
					wordText.setLayoutParams(params);
					// 设置最终位置
				  }
				  break;
			  case MotionEvent.ACTION_UP:
					// 手指离开屏幕时，把flag设为false
					flag = false;
				  break;
				}
			return true;
		}
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			 int flag = (Integer) seekBar.getTag();  
		        switch (flag)  
		        {  
		        case FLAG_SATURATION:  
		        	wordText.setTextSize(progress);
		            break;  
		        }  
		}
		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub
			
		}
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub
			
		}
}
